#!/usr/bin/env python
# encoding: utf-8
# @author: Lin Han
# @contact: voldemort22@126.com
# @file: deprecated_app.py
# @time: 2021/5/19 16:29
# @desc:
from datetime import timedelta

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm

from application.security.security_tools import Token, authenticate_user, ACCESS_TOKEN_EXPIRE_MINUTES, create_access_token, User, get_current_active_user
from utils.mongo_tools import retrieve_all_mongo_values
from views.configs import USER_COLLECTION

security_router = APIRouter(
    prefix="/api/security",
    tags=["security"],
)


@security_router.post("/v1/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    users = retrieve_all_mongo_values({}, collection_name=USER_COLLECTION)
    print(users)
    users_dict = {i["username"]: i for i in users}
    print(users)
    user = authenticate_user(users_dict, form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}


@security_router.get("/v1/users/me/", response_model=User)
async def read_users_me(current_user: User = Depends(get_current_active_user)):
    return current_user


@security_router.get("/v1/users/me/items/")
async def read_own_items(current_user: User = Depends(get_current_active_user)):
    return [{"item_id": "Foo", "owner": current_user.username}]


if __name__ == '__main__':
    import os
    import uvicorn

    module = os.path.basename(__file__).split(".")[0]
    print(module)
    uvicorn.run(f'{module}:app', host="0.0.0.0", port=8000, reload=True, debug=True)
